import { WebSocketData } from '@/util/DataStrcutures.js'
import EventEmitter from '@/util/EventEmitter.js'
import Vue from 'vue'
/**
 * @type {WebSocket}
 */
let socket = null
/**
 * 用于保存用户ID
 */
let userinfo = JSON.parse(localStorage.getItem('HuiLY'))?.userinfo
let reconnection = 0;
let userID = userinfo ? userinfo.id : null
let socketEventMessageEmitter = new EventEmitter()
/**
 * @param {{userID:string}} option 
 * @returns {Promise<WebSocket>}
 */
function _initWebSocket(option) {
    //  socket未建立，或者已经关闭，从新赋值，旧的socket需要被垃圾回收--》删除全部的引用
    if (!socket || socket.readyState !== WebSocket.OPEN) {
        if (!(option && option.userID)) return Promise.reject('获取用户信息后再建立连接!')
        userID = option.userID
        // 返回一个promise，包含socke对象，这样就可以进行对象
        return new Promise((resolve, reject) => {
            // 这里直接赋值导致
            socket = new WebSocket('ws://127.0.0.1:8088/socket')
            // 所有用户登录后都进行一个socket连接维持
            socket.addEventListener('open', function (event) {
                console.log('WebSocket 连接成功！');
                // 发送初始化信息
                let requestData = new WebSocketData('', {
                    _initInfo: true,
                    userID: option.userID
                })
                this.send(JSON.stringify(requestData))
            });

            socket.addEventListener('message', function (event) {
                /**
                 * @type {WebSocketData}
                 */
                let responseData = event.data;
                // 触发事件，把信息传出去
                console.log(event);
                socketEventMessageEmitter.emit('socketMessage', JSON.parse(responseData))
            });
            socket.addEventListener('error', function (event) {
                console.log('socket发生错误，200ms后进行重连!');
                setTimeout(() => {
                    _initWebSocket({ userID }).then((socket) => {
                        Vue.prototype.$socket = socket
                    }).catch(_ => { })
                }, 200)
            })
            socket.addEventListener('close', function (event) {
                /**
                 * @type {{code:boolean}}
                 */
                let reason = true
                if (event.reason.length) {
                    try {
                        reason = JSON.parse(event.reason).code != 'huily'
                    } catch (error) {
                        return
                    }
                }
                if (reason) {
                    console.log('socket断开,1000ms后进行重连');
                    setTimeout(() => {
                        _initWebSocket({ userID }).then((socket) => {
                            Vue.prototype.$socket = socket
                        }).catch(_ => { })
                    }, 1000)
                }
            })
            resolve(socket)
        })
    }
    else return Promise.resolve(socket)
}


/**
 * 定义send方法，使用自定义数据结构
 * @param {string} msg
 * @param {{sendID:string,receiverID:string}} options
 */
function _send_huily(msg, options) {
    return new Promise((resolve, reject) => {
        if (socket) {
            if (socket.readyState === WebSocket.OPEN) {
                let data = new WebSocketData(msg, {
                    _initInfo: false,
                    receiverID: options.receiverID,
                    sendID: options.sendID
                })
                // socket.send(encodeURIComponent(JSON.stringify(data)))
                socket.send(JSON.stringify(data))
                resolve()
            } else reject('socket连接已关闭')
        }
        else {
            console.log('socket在200ms重连');
            _initWebSocket({ userID })
            reject('socket对象不存在')
        }
    })
}


export default _initWebSocket
export {
    _send_huily,
    socketEventMessageEmitter,
    socket
}